package cn.lgp6.ziyou_util.music.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint(value = "/music/chat")
public class MusicChatSocketController {
    /** 记录当前在线连接数 */
    private static volatile AtomicInteger onlineCount = new AtomicInteger(0);
    private static volatile Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public synchronized void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        sessionMap.put(session.getId(),session);
        print("有新连接"+session.getId()+"加入,当前在线人数为:"+onlineCount.get());
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        System.out.println(requestParameterMap);
        Map<String,String> map=new HashMap<String, String>();
        map.put("type","system");
        map.put("message","系统通知:@"+session.getId()+"风度翩翩的进入了房间");
        map.put("count",String.valueOf(onlineCount.get()));
        sendMessageGroup(JSON.toJSONString(map),session,0);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public synchronized void onClose(Session session) {
        sessionMap.remove(session.getId());
        onlineCount.decrementAndGet(); // 在线数减1
        print("有一连接"+session.getId()+"关闭,当前在线人数为"+onlineCount.get());
        Map<String,String> map=new HashMap<String, String>();
        map.put("type","system");
        map.put("message","系统通知:@"+session.getId()+"离开了房间");
        map.put("count",String.valueOf(onlineCount.get()));
        sendMessageGroup(JSON.toJSONString(map),session,0);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public synchronized void onMessage(String message, Session session) {
        print("服务器接收到"+session.getId()+"的消息:"+message);
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Map<String,String> map=new HashMap<String, String>();
        map.put("type","message");
        map.put("message","@"+session.getId()+message);
        map.put("time",format);
        map.containsKey("1");
        sendMessageGroup(JSON.toJSONString(map),session,1);

    }

    @OnError
    public synchronized void onError(Session session, Throwable error) {
        print("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    synchronized private void sendMessage(String message, Session toSession,int type) {
        try {
            sendMessageGroup(message,toSession,type);
        } catch (Exception e) {
            print("服务端发送消息给客户端失败：{}"+e.getLocalizedMessage());
        }
    }
    /**
     * 群发
     */
    synchronized private   void sendMessageGroup(String message,Session session,int type) {
        print("服务端群发消息:"+ message);
        // type 0 系统 1 用户
        try {

            for (String s : sessionMap.keySet()) {
                if (type==1){
                    if (!s.equals(session.getId())){
                        sessionMap.get(s).getBasicRemote().sendText(message);
                    }
                }else{
                    sessionMap.get(s).getBasicRemote().sendText(message);
                }
            }
//            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            print("服务端发送消息给客户端失败：{}"+e.getLocalizedMessage());
        }
    }


    private void print(String log){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+":"+log);
    }
    @Scheduled(fixedDelay = 1000*60*10)
    public void tips(){
        Map<String,String> map=new HashMap<String, String>();
        map.put("type","system");
        map.put("message","系统通知:站点管理员监控提示:请注意您的一言一行,认真遵守法律与道德规范,本站管理员将24小时不定时对站内信息监控,若发现违规行为,将依据违规行为进行处置,严重者将直接移送公安机关处理!感谢您对LGP聊天室的支持,祝您有一个良好的聊天体验!如果您对本站有更好的建议,可以发送邮件至lgp1022@foxmail.com与站点管理员联系!");
        map.put("count",String.valueOf(onlineCount.get()));
        sendMessageGroup(JSON.toJSONString(map),sessionMap.get(1),0);
        System.out.println("发送定时提示");
    }
}
